package com.example.demo.queue;

import org.jetbrains.annotations.NotNull;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;


/**
 * @author Smile to life
 */
public class Task implements Delayed {

    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

    private String name;
    private long time;
    private LocalDateTime offerTime = LocalDateTime.now();
    private long start = System.currentTimeMillis();

    /**
     * 构造函数，任务名称，延时时间
     *
     * @param name
     * @param time
     */
    public Task(String name, long time) {
        this.name = name;
        this.time = time;
    }

    /**
     * 以给定的时间单位返回与此对象关联的剩余延迟,用过期时间-当前时间
     *
     * @param unit 单位时间单位
     * @return 返回剩余延迟, 零或负值表示*延迟已经过去
     */
    @Override
    public long getDelay(@NotNull TimeUnit unit) {
        return unit.convert((start + time) - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 为加入到队列中的对象进行排序，以保证延时时间短的对象能够先被消费掉。
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(@NotNull Delayed o) {
        Task o1 = (Task) o;
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    @Override
    public String toString() {
        return "Task{" +
                "name='" + name + '\'' +
                ", time=" + time +
                ", offerTime=" + formatter.format(offerTime) +
                ", takeTime=" + formatter.format(LocalDateTime.now()) +
                '}';
    }
}
